package datastructure.map;

/**
 * @author XY
 * @version 1.0
 * @date 2021/11/11 10:31
 * @Description 以链表为基础的映射
 */
public class LInkedLIstMap<K,V> implements Map<K,V> {

    private class Node {
        public K key;
        public V value;
        public Node next;

        public Node(K key,V value ,Node next){
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public Node(K key){
            this(key,null,null);
        }

        public Node(){
            this(null,null,null);
        }

        @Override
        public String toString() {
            return key.toString()+":"+value.toString();
        }
    }

    private Node dummyHead;
    private int size;

    public LInkedLIstMap(){
        dummyHead = new Node();
        size = 0;
    }

    @Override
    public void add(K key, V value) {
        Node node = getNode(key);
        if(node==null){
            dummyHead.next = new Node(key,value,dummyHead.next);
            size++;
        }else{
            //这里设计为覆盖原有值，也可以设计为不可重复添加
            node.value=value;
        }
    }

    @Override
    public V remove(K key) {
        Node prev= dummyHead;
        while (prev.next!=null){
            if(prev.next.key.equals(key)){
                break;
            }
            prev = prev.next;
        }
        if(prev.next!=null){
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            return delNode.value;
        }
        return null;
    }

    @Override
    public boolean contains(K key) {
        return getNode(key)!=null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        if(node!=null){
            return node.value;
        }
        return null;
    }

    public Node getNode(K key) {
        Node cur = dummyHead.next;
        while(cur!=null){
            if(cur.key.equals(key)){
                return cur;
            }
        }
        return null;
    }

    @Override
    public void set(K key, V value) {
        Node node = getNode(key);
        if(node == null){
            throw  new RuntimeException(key+" is not exist!");
        }
        node.value = value;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }
}
